#! /usr/bin env python
# coding:utf-8
# 业务逻辑

import espider.config as Config
import pymysql
import json
import time
import espider.utils as Utils
from espider.app.jd.jd_exception import JdException


class JdLogic:
    def __init__(self):
        self.db = pymysql.connect(
            host=Config.DB.get("host"),
            port=Config.DB.get("port"),
            user=Config.DB.get("user"),
            passwd=Config.DB.get("passwd"),
            db=Config.DB.get("db"),
            charset=Config.DB.get("charset")
        )
        self.cursor = self.db.cursor(cursor=pymysql.cursors.DictCursor)

    # save data
    def saveData(self):
        totalCount = accounts = 0
        if 0 == totalCount or 0 == len(accounts):
            return
        # 入库account表
        for i in accounts:
            accountId = i.get('accountId', 0)
            sql = 'select * from %s where `account_id` = "%d"' % (
                Config.TableMap.get('HUAWEI_AGENCYS_TABLE'), accountId)
            Utils.D("Query: %s" % sql)
            res = self.cursor.execute(sql)  # 如果找到返回主键id，否则返回0
            status = Config.AUDIT_OK if i['status'] == 'AUDITED' else Config.AUDIT_FAIL
            jsondata = json.dumps({
                "createTime": i.get('createTime', ''),
                "lastDaySpent": i.get('lastDaySpent', ''),
                "todaySpent": i.get('todaySpent', ''),
                "status": i.get('status', '')
            })
            valuesTuple = (
                i.get('corpName', ''),
                status,
                i.get('balance', 0),
                accountId,
                jsondata,
            )
            xx = time.strftime("%Y%m%d", time.localtime())
            batch = self.api.getHbaseConn("account")
            rowkey = '{}|{}|{}|{}|{}'.format(str(accountId)[-1:], xx, self.mediaId, accountId, self.agencyId)
            data_list = json.dumps(jsondata)
            batch.put(row=rowkey, data={'info:data': str(data_list)})
            batch.send()
            try:
                if (res):
                    # update
                    sets = {
                        "`corp_name` = '%s'" % valuesTuple[0],
                        "`status` = %s" % valuesTuple[1],
                        "`balance` = %s" % valuesTuple[2],
                        "`account_id` = '%s'" % valuesTuple[3],
                        "`jsondata` = '%s'" % valuesTuple[4],
                    }
                    sql = "update %s set %s where `account_id` = '%s'" % (
                        Config.TableMap.get('HUAWEI_AGENCYS_TABLE'), ",".join(sets), accountId)
                    Utils.D("Update: %s" % sql)
                else:
                    # insert
                    values = "'%s',%s,%s,'%s','%s'" % valuesTuple
                    sql = "insert into %s (`corp_name`, `status`, `balance`, `account_id`, `jsondata`) values (%s)" % (
                        Config.TableMap.get('HUAWEI_AGENCYS_TABLE'), values)
                    Utils.D("Insert: %s" % sql)
                self.cursor.execute(sql)
            except:
                raise JdException(Config.KD_ERROR, [
                    "sql: %s" % sql,
                    "value: %s" % json.dumps(valuesTuple)
                ])

        # 提交事物
        self.db.commit()
